package org.vs.handler.responsibilitychain.vote;

import com.alibaba.fastjson2.JSON;
import org.springframework.stereotype.Component;
import org.vs.annotation.CheckBalance;
import org.vs.contract.VoteContract;
import org.vs.domain.model.TVote;
import org.vs.domain.vo.ProgressVO;
import org.vs.handler.responsibilitychain.BaseResponsibilityChainHandler;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.time.Instant;
import java.time.ZoneOffset;

@Component
public class VotePublishInfoHandler extends BaseResponsibilityChainHandler {
    @Resource
    private VotePublishOptionHandler votePublishOptionHandler;

    @CheckBalance
    @Override
    protected boolean customerHandler(Object obj) {
        try {
            VotePublishHandlerEO votePublishHandlerEO = (VotePublishHandlerEO) obj;

            votePublishHandlerEO.setCount(votePublishHandlerEO.getCount() + 1);
            setHandler(votePublishOptionHandler);
            setMessage(votePublishHandlerEO.getHashcode(), JSON.toJSONString(ProgressVO
                    .builder()
                    .progress((100 / voteCount) * votePublishHandlerEO.getCount())
                    .info("完成基础信息写入")
                    .build()));

            TVote vote = votePublishHandlerEO.getVote();
            Instant startTime = vote.getStartTime().toInstant(ZoneOffset.UTC);
            Instant endTime = vote.getEndTime().toInstant(ZoneOffset.UTC);

            VoteContract.VoteInfo voteInfo = new VoteContract.VoteInfo(
                    vote.getTitle(),
                    vote.getImage(),
                    vote.getDescription(),
                    BigInteger.valueOf(startTime.toEpochMilli() / 1000),
                    BigInteger.valueOf(endTime.toEpochMilli() / 1000)
            );
            votePublishHandlerEO.getVoteContract().setVoteInfo(voteInfo).send();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }
}
